import React from "react";
import * as antd from "antd";
class SetStateTest extends React.Component {
  constructor(props) {
    super(props);
  }
  state = {
    count: 0,
  };

  componentDidMount() {
    const addBtn = document.getElementById("addBtn");
    addBtn.addEventListener("click", () => {
      // setState参数如果是对象则是同步
      this.setState({
        count: this.state.count + 5,
      });
      this.setState({
        count: this.state.count + 5,
      });
      this.setState({
        count: this.state.count + 5,
      });
      console.log(this.state.count);
    });
  }

  add = () => {
    this.setState({
      count: this.state.count + 5,
    });
    console.log(this.state.count,"此处的count总是与真实的count差5")    
  };
  add1 = () => {
    this.setState({
      count: this.state.count + 5,
    },() => {
        console.log(this.state.count,"此处的count总是与真实的count相同")    
    });
   
  };
  add2 = () => {
    // setState参数如果是对象则是异步
    this.setState({
      count: this.state.count + 5,
    });
    this.setState({
      count: this.state.count + 5,
    });
    this.setState({
      count: this.state.count + 5,
    });
  };
  add3 = () => {
    // setState在setTimeout中是同步
    setTimeout(() => {
      this.setState({
        count: this.state.count + 5,
      });
      this.setState({
        count: this.state.count + 5,
      });
      this.setState({
        count: this.state.count + 5,
      });
    });
  };
  add4 = () => {
    // setState的参数是函数则是同步
    this.setState((state, props) => ({ count: state.count + 5 }));
    this.setState((state, props) => ({ count: state.count + 5 }));
    this.setState((state, props) => ({ count: state.count + 5 }));
  };
  add5 = () => {
    // 回调函数是同步
    this.setState({ count: this.state.count + 5 }, () => {
      this.setState({ count: this.state.count + 5 }, () => {
        this.setState({ count: this.state.count + 5 });
      });
    });
  };
  render() {
    return (
      <div>
        <h3>setState同步,异步的问题</h3>
        State.count: {this.state.count}
        <antd.Divider></antd.Divider>
        <antd.Button key={1} onClick={this.add}>
         +5(正常,获取值异常(查看console))
        </antd.Button>
        <antd.Button key={11} onClick={this.add1}>
          +5(正常,获取值正常(查看console))
        </antd.Button>
        <antd.Button key={2} onClick={this.add2}>
          +15(有问题)
        </antd.Button>
        <button id="addBtn">+15(正常,原生监听函数)</button>
        <antd.Button key={3} onClick={this.add3}>
          +15(正常,setTimeou中调用setState)
        </antd.Button>
        <antd.Button key={4} onClick={this.add4}>
          +15(正常，setState参数是函数)
        </antd.Button>
        <antd.Button key={5} onClick={this.add5}>
          +15(正常,setState回调函数)
        </antd.Button>
      </div>
    );
  }
}
export default SetStateTest;
